using System;
using System.Collections;

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using Banshee.Base;
using Banshee.Sources;
using Banshee.Widgets;
using Banshee.Winforms;
namespace Banshee
{
    public partial class PlayListView : UserControl
    {
        PlaylistModel model;
        TrackInfo selectedTrack;
        private Label viewlabel;

        public Label Viewlabel
        {
            get { return viewlabel; }
            set { viewlabel = value; }
        }
        public TrackInfo SelectedTrackInfo
        {
            get { return selectedTrack; }
            set { selectedTrack = value; }
        }
        public PlaylistModel Model
        {
            get { return model; }
            set
            {
                model = value;
                if (model != null)
                {
                    
                    model.Updated += new EventHandler(model_Updated);
                }
            }
        }
        DataGridViewCellStyle style = null;
        public void RefreshTracks()
        {
            trackView.Rows.Clear();
            ThreadAssist.Spawn(new System.Threading.ThreadStart(setSource), true);
            trackView.Invalidate(true);
        }
        void model_Cleared(object sender, EventArgs e)
        {
            this.BeginInvoke((MethodInvoker)delegate()
            {
                
            });
        }
        public IList<TrackInfo> SelectedTrackInfoMultiple
        {
            get
            {
                if (trackView.SelectedRows.Count == 0)
                {
                    return null;
                }

                List<TrackInfo> list = new List<TrackInfo>();

                foreach (DataGridViewRow row in trackView.SelectedRows )
                {
                    string uri = row.Cells[uriColumn.Index].Value.ToString();
                    list.Add(PathTreeInfo(uri));
                }

                return list;
            }
        }
        void model_Updated(object sender, EventArgs e)
        {
            ThreadAssist.Spawn(new System.Threading.ThreadStart(setSource), true);
        }
        public PlayListView()
        {
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            InitializeComponent();
        }
        public bool PlaySelected()
        {
            return false;
        }
        public void PlayTrack()
        {

            string uri = trackView.SelectedRows[0].Cells[uriColumn.Index].Value.ToString();
            model.PlayIter(uri);

        }
        void setSource()
        {

                BeginInvoke((MethodInvoker)delegate() {
                    
                    if(SourceManager.ActiveSource.GetType() == typeof(LibrarySource))
                        titleColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    else 
                        titleColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    //Banshee.Controls.SortableBindingList<TrackInfo> trx = new Banshee.Controls.SortableBindingList<TrackInfo>(model.Tracks);
                    //Okay sorting is now working on my nerves but not on the grid;
                    trackView.SuspendDraw = true;
                    tracksBindingSource.DataSource = model.Source.Tracks;
                    trackView.SuspendDraw = false;
                });
            
        }
        
        TrackInfo PathTreeInfo(string path)
        {
            TrackInfo pathtrackinfo = null;
            foreach (TrackInfo track in SourceManager.ActiveSource.Tracks)
            {
                if (track.Uri.ToString() == path)
                {
                    pathtrackinfo = track;
                    break;
                }
            }
            return pathtrackinfo;
        }
        public void SelectPlaying()
        {
            
        }
        public void UpdateView()
        {
            ScrollToPlaying();
        }

        int current_index
        {
            get
            {
                int index = 0;
                IList<TrackInfo> info = (IList<TrackInfo>)tracksBindingSource.DataSource;
                for (int i = 0; i < info.Count; i++)
                {
                    TrackInfo track = info[i];
                    if (PlayerEngineCore.CurrentTrack != null)
                    {
                        if (track.Uri == PlayerEngineCore.CurrentTrack.Uri)
                            index = i;
                    }
                }
                return index;
            }
        }
        DataGridViewRow currenttrack;
        public void ScrollToPlaying()
        {
            //Cornel I dont want to loop through each track setting the cellstyle
            //       Although i would like to let this work like banshee
            
            if (trackView.Rows.Count > 0)
            {

                trackView.DefaultCellStyle = style;
                currenttrack = trackView.Rows[current_index];
                currenttrack.DefaultCellStyle.Font = new Font(trackView.DefaultCellStyle.Font, FontStyle.Bold);
                trackView.FirstDisplayedScrollingRowIndex = current_index;
                //this wont work with shuffle but i will do that when i get there 
                if(current_index != 0)
                    trackView.Rows[current_index - 1].DefaultCellStyle.Font = new Font(trackView.DefaultCellStyle.Font, FontStyle.Regular); 
                if (current_index != trackView.Rows.Count)
                    trackView.Rows[current_index + 1].DefaultCellStyle.Font = new Font(trackView.DefaultCellStyle.Font, FontStyle.Regular); 
            }
        }
        public void ColumnChooser()
        {

            TrackViewColumnWindow chooser = new TrackViewColumnWindow();
            chooser.Columns = trackView.Columns;
            chooser.ShowDialog(this);
            SaveColums();
        }
        void handleDragDrop()
        {
        }
        public void SaveColums()
        {
            for (int i = 0; i < trackView.Columns.Count; i++)
            {
                DataGridViewColumn col = trackView.Columns[i];
                if (col.HeaderText != "Uri")
                {

                    if (col.HeaderText == "Title")
                    {
                        if (!TitleVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            TitleVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Artist")
                    {
                        if (!ArtistVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            ArtistVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Album")
                    {
                        if (!AlbumVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            ArtistVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Genre")
                    {
                        if (!GenreVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            GenreVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Time")
                    {
                        if (!TimeVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            TimeVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Year")
                    {
                        if (!YearVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            YearVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Track")
                    {
                        if (!TrackVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            TrackVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Last Played")
                    {
                        if (!LastPlayVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            LastPlayVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Rating")
                    {
                        if (!RatingVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            RatingVisibleSchema.Set(col.Visible);
                        }
                    }
                    else if (col.HeaderText == "Plays")
                    {
                        if (!PlayCountVisibleSchema.Equals(Banshee.Configuration.SchemaEntry<bool>.Zero))
                        {
                            PlayCountVisibleSchema.Set(col.Visible);
                        }
                    }
                }
            }
            
        }
            
        public void LoadColumns()
        {
            for (int i = 0; i < trackView.Columns.Count; i++)
            {
                DataGridViewColumn col = trackView.Columns[i];

                if (col.HeaderText == "Title")
                    col.Visible = TitleVisibleSchema.Get();
                else if (col.HeaderText == "Artist")
                    col.Visible = ArtistVisibleSchema.Get();
                else if (col.HeaderText == "Album")
                    col.Visible = AlbumVisibleSchema.Get();
                else if (col.HeaderText == "Genre")
                    col.Visible = GenreVisibleSchema.Get();
                else if (col.HeaderText == "Time")
                    col.Visible = TimeVisibleSchema.Get();
                else if (col.HeaderText == "Year")
                    col.Visible = YearVisibleSchema.Get();
                else if (col.HeaderText == "Track")
                    col.Visible = TrackVisibleSchema.Get();
                else if (col.HeaderText == "Last Played")
                    col.Visible = LastPlayVisibleSchema.Get();
                else if (col.HeaderText == "Rating")
                    col.Visible = RatingVisibleSchema.Get();
                else if (col.HeaderText == "Plays")
                    col.Visible = PlayCountVisibleSchema.Get();

            
            }
        }
        #region Column Schemas
        public static Banshee.Configuration.SchemaEntry<bool> year_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "yearvisible",
        false,
        "Visiblity",
        "Visibility of Year column"
        );
        protected  Banshee.Configuration.SchemaEntry<bool> YearVisibleSchema
        {
            get { return year_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> title_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "titlevisible",
        true,
        "Visiblity",
        "Visibility of Title column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> TitleVisibleSchema
        {
            get { return title_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> artist_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "artistvisible",
        true,
        "Visiblity",
        "Visibility of Artist column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> ArtistVisibleSchema
        {
            get { return artist_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> album_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "albumvisible",
        true,
        "Visiblity",
        "Visibility of Album column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> AlbumVisibleSchema
        {
            get { return album_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> genre_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "genrevisible",
        false,
        "Visiblity",
        "Visibility of Genre column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> GenreVisibleSchema
        {
            get { return genre_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> tracknumber_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "tracknumbervisible",
        true,
        "Visiblity",
        "Visibility of Track Number column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> TrackVisibleSchema
        {
            get { return tracknumber_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> time_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "durationvisible",
        true,
        "Visiblity",
        "Visibility of Duration column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> TimeVisibleSchema
        {
            get { return time_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> lastplay_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "lastplayvisible",
        false,
        "Visiblity",
        "Visibility of Track Number column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> LastPlayVisibleSchema
        {
            get { return lastplay_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> playcount_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "playcountvisible",
        false,
        "Visiblity",
        "Visibility of Play Count column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> PlayCountVisibleSchema
        {
            get { return playcount_schema; }
        }
        public static Banshee.Configuration.SchemaEntry<bool> rating_schema = new Banshee.Configuration.SchemaEntry<bool>(
        "view_columns", "ratingvisible",
        false,
        "Visiblity",
        "Visibility of Rating column"
        );
        protected Banshee.Configuration.SchemaEntry<bool> RatingVisibleSchema
        {
            get { return rating_schema; }
        }
        #endregion
        private void PlayListViewI_Load(object sender, EventArgs e)
        {
           //LoadColumns();
            style = this.trackView.DefaultCellStyle;
        }
        private void grid_menu_Opening(object sender, CancelEventArgs e)
        {
          addToPlaylistToolStripMenuItem.DropDownItems.Clear();
          ToolStripMenuItem item;
          foreach(Source source in SourceManager.Sources){
                if (source.GetType() != typeof(LibrarySource))
                {
                    item = new ToolStripMenuItem(source.Name);
                    item.Tag = source;
                    item.Click += new EventHandler(item_Click);
                    addToPlaylistToolStripMenuItem.DropDownItems.Add(item);
                }
            }
        }

        void item_Click(object sender, EventArgs e)
        {
            Source source = ((ToolStripMenuItem)sender).Tag as Source;
            for (int i = 0; i < trackView.SelectedRows.Count; i++)
            {
                TrackInfo track = PathTreeInfo(trackView.SelectedRows[i].Cells[uriColumn.Index].Value.ToString());
                source.AddTrack(track);
                source.Commit();
            }
        }


        private void removeTrackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //SourceManager.ActiveSource.RemoveTrack(PathTreeInfo(trackView.SelectedRows[0].Cells[uriColumn.Index].Value.ToString()));

            SourceManager.ActiveSource.RemoveTrack(SelectedTrackInfoMultiple);
            SourceManager.ActiveSource.Commit();
           // RefreshTracks();
            
        }

        private void trackView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (trackView.SelectedRows.Count > 0)
            {
                DataGridViewRow item = trackView.SelectedRows[0];
               // TrackInfo track = PathTreeInfo(item.Cells[uriColumn.Index].Value.ToString());
                //PlayerEngineCore.OpenPlay(track);
                model.PlayIter(item.Cells[uriColumn.Index].Value.ToString());
            }
        }
        Banshee.Base.Gui.SourceView sourceView;

        public Banshee.Base.Gui.SourceView SourceView
        {
            get { return sourceView; }
            set { sourceView = value; }
        }
        private void trackView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Clicks == 2)
            {
                trackView_CellDoubleClick(sender, new DataGridViewCellEventArgs(e.ColumnIndex,e.RowIndex));
            }
            else if (e.Button == MouseButtons.Right)
            {
                trackView.ContextMenuStrip.Show();
            }
            else
            {
                DataGridViewSelectedRowCollection rows = trackView.SelectedRows;
                if (sourceView != null)
                {
                    sourceView.DragRows = rows;
                    trackView.DoDragDrop(rows, DragDropEffects.Copy);
                }
            }
            
        }


    }
    

}
